package com.zzq.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zzq.pojo.Permission;
import com.zzq.pojo.User;
import com.zzq.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * 幼儿猿大班
 * 2021/7/28
 */
@Component
public class MyUserInfo implements UserDetailsService {

    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        // 去数据库里查用户信息
       User user= userService.findUserByUserName(s);

        if (user==null) {
            // 数据库中没有此用户，用户名错误
            return null;
        }

        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Permission permission : user.getPermissionList()) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),grantedAuthorities);

    }
}
